<template>
  <div class="app-container">
    <el-row  v-if="!convertBuiness">
      <el-col :span="24">
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
          <el-form-item label="活动名称" prop="activityName">
            <el-input
              v-model="queryParams.activityName"
              placeholder="请输入活动名称"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="活动时间" prop="initiationTime">
            <el-date-picker clearable v-model="queryParams.initStartTime" type="datetime" value-format="yyyy-MM-dd HH:mm" placeholder="请选择开始时间">
            </el-date-picker>
            至
            <el-date-picker clearable v-model="queryParams.initEndTime" type="datetime" value-format="yyyy-MM-dd HH:mm" placeholder="请选择结束时间">
            </el-date-picker>
          </el-form-item>



          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
          <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>
        </el-row>
        <div style="width: 100%;height: 90vh;overflow:auto; margin-bottom: 30%;padding-bottom: 18%;position: relative;">
        <el-table :row-style="{ height: '30px' }"  :cell-style="{ padding: '0px' }" height="450" border  v-loading="loading" :data="trainingList" highlight-current-row >
          <el-table-column
            label="序号" type="index" :index="indexMethod"  align="center"/>
          <el-table-column label="活动名称" align="center" prop="activityName"  v-if="columns[1].visible" :show-overflow-tooltip="true"/>
          <el-table-column label="发起单位" align="center" prop="organizationName" v-if="columns[2].visible" :show-overflow-tooltip="true"/>
          <el-table-column label="主办单位" align="center" prop="sponsor" v-if="columns[3].visible" :show-overflow-tooltip="true"/>
          <el-table-column label="类别" align="center" prop="type" v-if="columns[4].visible"
                           :show-overflow-tooltip="true" >
            <template slot-scope="scope">
              <dict-tag :options="dict.type.activity_type" :value="scope.row.type" />
            </template>
          </el-table-column>
          <el-table-column label="发起时间" align="center" prop="initiationTime" width="120" v-if="columns[5].visible">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.initiationTime, '{y}-{m}-{d}') }}</span>
            </template>
          </el-table-column>
          <el-table-column label="形式" align="center" prop="lays" v-if="columns[5].visible" />
          <el-table-column label="开始时间" align="center" prop="startTime" width="130" v-if="columns[6].visible">
            <template slot-scope="scope">
              <span>{{ parseUTCTime(scope.row.startTime, '{y}-{m}-{d} {hh}:{mm}') }}</span>
            </template>
          </el-table-column>
          <el-table-column label="结束时间" align="center" prop="endTime" width="130" v-if="columns[7].visible">
            <template slot-scope="scope">
              <span>{{ parseUTCTime(scope.row.endTime, '{y}-{m}-{d} {hh}:{mm}') }}</span>
            </template>
          </el-table-column>
          <el-table-column label="地点" align="center" prop="location" v-if="columns[8].visible" :show-overflow-tooltip="true"/>
          <el-table-column label="联系人" align="center" prop="contacts" v-if="columns[12].visible" />
          <el-table-column label="联系电话" align="center" prop="telephone" v-if="columns[13].visible" :show-overflow-tooltip="true"/>
          <el-table-column label="报名截止" align="center" prop="deadlineTime" width="120" v-if="columns[14].visible">
            <template slot-scope="scope">
              <span>{{ parseUTCTime(scope.row.deadlineTime, '{y}-{m}-{d}') }}</span>
            </template>
          </el-table-column>
          <el-table-column label="状态" align="center" prop="status" v-if="columns[0].visible" />
          <el-table-column label="创建人" align="center" prop="creationName" v-if="columns[10].visible"  :show-overflow-tooltip="true" width="100"/>
          <el-table-column label="创建时间" align="center" prop="creationTime" width="120" v-if="columns[11].visible">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.creationTime, '{y}-{m}-{d}') }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="80px" fixed="right">
            <template slot-scope="scope">
<!--              :disabled="!(scope.row.status === '审核' && isBeforeDeadline(scope.row.deadlineTime))"-->
              <el-button
                :disabled="scope.row.status !== '审核'"
                size="mini"
                type="text"
                icon="el-icon-orange"
                @click="handleSelect(scope.row,scope.$index)"
                title="审核"
              ></el-button>
              <el-button
                :disabled="scope.row.status === '审核' && isBeforeDeadline(scope.row.deadlineTime)"
                size="mini"
                type="text"
                icon="el-icon-view"
                @click="handleScore(scope.row,scope.$index)"
                title="查看"
              ></el-button>
            </template>
          </el-table-column>
        </el-table>
        <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum"
                    :limit.sync="queryParams.pageSize" @pagination="getList" />
        </div>
      </el-col>
    </el-row>
    <!-- 添加或修改活动信息培训对话框 -->
    <el-dialog :title="title" :visible.sync="open"  width="700px" append-to-body @close="closeTrain">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px" :inline="true">
        <div v-if="addSign!==0">
          <el-descriptions title="">
            <el-descriptions-item label="序号">
              <el-tag size="medium">{{form.index}}</el-tag>
            </el-descriptions-item>
          </el-descriptions>
        </div>
        <el-form-item label="创建时间" prop="creationTime" >
          <el-date-picker clearable
                          v-model="form.creationTime"
                          type="date"
                          value-format="yyyy-MM-dd"
                          placeholder="请选择创建时间"
                          style="width: 202.5px"
                          disabled="true">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="活动名称" prop="activityName">
          <el-input v-model="form.activityName" placeholder="请输入活动名称"  :disabled="ReadOnly" style="width: 202.5px"/>
        </el-form-item>
        <el-form-item label="主办单位" prop="sponsor" label-width="80px">
          <el-input v-model="form.sponsor" type="textarea" placeholder="请选择主办单位" readonly :disabled="ReadOnly"
                    style="width: 500px"  />
        </el-form-item>
        <el-form-item label="协办单位" prop="organizer" label-width="80px">
          <el-input v-model="form.organizer" type="textarea" placeholder="请选择协办单位" readonly :disabled="ReadOnly"
                    style="width: 500px"  />
        </el-form-item>
        <el-form-item label="承办单位" prop="undertaker" label-width="80px">
          <el-input v-model="form.undertaker" type="textarea" placeholder="请选择承办单位" readonly :disabled="ReadOnly"
                    style="width: 500px"  />
        </el-form-item>
        <el-form-item label="发起时间" prop="initiationTime">
          <el-date-picker clearable
                          v-model="form.initiationTime"
                          type="date"
                          value-format="yyyy-MM-dd"
                          placeholder="请选择发起时间"
                          style="width: 202.5px"
                          :disabled="ReadOnly">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="类别" prop="type" label-width="80px">
          <el-select v-model="form.type" placeholder="请选择形式" style="width: 202.5px"    :disabled="ReadOnly">
            <el-option
              v-for="dict in dict.type.activity_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="形式" prop="lays">
          <el-select v-model="form.lays" placeholder="请选择形式"  style="width: 202.5px" :disabled="ReadOnly">
            <el-option label="线下" value="线下"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="开始时间" prop="startTime" >
          <el-date-picker
            v-model="form.startTime" type="datetime" placeholder="选择日期时间" value-format="yyyy-MM-dd HH:mm" :disabled="ReadOnly" :picker-options="{ disabledDate: dateOptions }" style="width: 202.5px">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="结束时间" prop="endTime" >
          <el-date-picker
            v-model="form.endTime" type="datetime" placeholder="选择日期时间" value-format="yyyy-MM-dd HH:mm" :disabled="ReadOnly" :picker-options="{ disabledDate: dateOptions }" style="width: 202.5px">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="地点" prop="location">
          <el-input v-model="form.location" placeholder="请输入地点" :disabled="ReadOnly" style="width: 202.5px" :title="ReadOnly ? form.location : ''"/>
        </el-form-item>
        <el-form-item label="联系人" prop="contacts">
          <el-input v-model="form.contacts" placeholder="请输入联系人" :disabled="ReadOnly" style="width: 202.5px"/>
        </el-form-item>
        <el-form-item label="联系电话" prop="telephone">
          <el-input v-model="form.telephone" placeholder="请输入联系电话" :disabled="ReadOnly" style="width: 202.5px"/>
        </el-form-item>
        <el-form-item label="报名截止" prop="deadlineTime">
          <el-date-picker clearable
                          v-model="form.deadlineTime"
                          type="datetime"
                          value-format="yyyy-MM-dd HH:mm"
                          placeholder="请选择报名截止"
                          style="width: 202.5px"
                          :disabled="ReadOnly">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="费用" prop="fee">
          <el-input v-model="form.fee" placeholder="请输入费用" :disabled="ReadOnly" style="width: 202.5px"/>
        </el-form-item>
        <el-form-item label="区域" prop="region" >
          <Treeselect v-model="form.region" :options="optionsArea"  style="width: 202.5px"  :flat="true" :show-count="true" :normalizer="normalizer"  placeholder="请选择区域" :disabled="ReadOnly" />
        </el-form-item>
        <el-form-item label="发送方式" prop="sendType">
          <el-radio-group v-model="form.sendType" :disabled="ReadOnly">
            <el-radio label="oneClick">一键发送</el-radio>
            <el-radio label="groupSend">分类群发</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="form.sendType === 'groupSend'" label="群发内容" prop="receiverName" >
          <el-input v-model="form.receiverName" type="textarea" placeholder="请输入内容"  style="width: 500px" @focus="handleTextAreaFocus" :disabled="ReadOnly"/>
        </el-form-item>
        <el-form-item label="附件" prop="uploadFile" >
          <file-view  v-if="show"  :limit="1" :type="typeSelect" :businessId="form.fileUpload" :businessCode="businessCode"  style="width: 500px"></file-view>
        </el-form-item>
        <el-form-item label="配图" prop="activityPicture">
          <file-view v-if="show" :limit="1" :type="typeSelect2" :businessId="form.activityPicture" :businessCode="businessCode"
                     style="width: 500px"></file-view>
        </el-form-item>
        <el-form-item label="审核状态" prop="examineStatus" label-width="110px" >
          <el-radio-group v-model="form.examineStatus" :disabled="examineRead">
            <el-radio label="through">审核通过</el-radio>
            <el-radio label="termination">审核不通过</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="终止原因" prop="endReason" v-if="form.examineStatus === 'termination'" label-width="110px">
          <el-input v-model="form.endReason" type="textarea" placeholder="请输入终止原因"    style="width: 465px" show-word-limit :disabled="examineRead"/>
        </el-form-item>
        <el-form-item label="参训人数" prop="partPersonNum" v-if="addSign===3 && form.examineStatus =='through'" label-width="100px" >
          <el-input v-model="form.partPersonNum" placeholder="请输入参训人数" disabled="true" style="width: 202.5px"/>
        </el-form-item>
        <el-form-item label="参训企业数量" prop="partEnterNum" v-if="addSign===3 && form.examineStatus =='through'" label-width="100px" >
          <el-input v-model="form.partEnterNum" placeholder="请输入参训企业数量" disabled="true" style="width: 202.5px"/>
        </el-form-item>
        <el-form-item label="满意度平均分" prop="satisfactionScore" v-if="addSign===3 && form.examineStatus =='through'" label-width="100px">
          <el-input v-model="form.satisfactionScore" placeholder="请输入满意度平均分" disabled="true" style="width: 202.5px"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer" style="display: flex; justify-content: center; align-items: center;">
        <el-button type="primary" v-if="form.status==='审核'" @click="submitForm(form.activityId)">审 核</el-button>
        <el-button @click="cancel">关 闭</el-button>
      </div>

    </el-dialog>
    <el-dialog :title="title" :visible.sync="openUser" width="1400px" append-to-body >
      <el-scrollbar>

        <div class="content-box">
          <BusinessInfo :markAs="1" @change="close" @ok="selectEnterprise" :enterprise="1" :isTree="false" :train="true">
          </BusinessInfo></div>
      </el-scrollbar>
    </el-dialog>
    <div v-if="convertBuiness">
      <Operate @change="closeEle" :opt="'add'"  ></Operate>
    </div>
    <select-user ref="select"  :type="userType" :sign="sign" @ok="selectUser"></select-user>
  </div>
</template>

<script>
import { listTrainingExamine, getTraining, examine, endStatus, updateTraining } from "@/api/activity/training";
import {listType} from "@/api/maintype/type";
import MainType from "@/components/MainType/index"
import FileView from "@/components/FileView/index"
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import BusinessInfo from "../../enterprise/info/index.vue";
import SelectUser from "../../system/role/selectUser.vue";
import Operate from "../../enterprise/businessinfo/operate.vue";
import { listArea } from "@/api/area/area";
export default {
  name: "Training",
  components:{Operate, SelectUser, BusinessInfo, Treeselect, MainType,FileView},
  dicts: ['activity_type'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      typeCode:'train',
      typeSelect2:1,
      // 活动信息培训表格数据
      trainingList: [],
      // 弹出层标题
      title: "",
      //详情状态
      ReadOnly:false,
      examineRead:false,
      // 是否显示弹出层
      open: false,
      //判断对话框是否新增或编辑
      addSign:0,
      //图片的标志位
      show:false,
      typeSelect:0,
      businessCode:'train',
      //主分类
      options:null,
      userType:"1",
      //行政区域
      optionsArea:null,
      sign:'1',
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 15,
        activityName: null,
        initStartTime: null,
        initEndTime:null
      },
      convertBuiness:false,
      openUser:false,
      // 表单校验
      rules: {
        examineStatus: [
          { required: true, message: '请选择状态', trigger: 'change' }
        ],
        endReason: [
          { required: true, message: '请输入终止原因', trigger: 'blur', when: (data) => data.sendType === 'termination' },
        ],
      },
      // 列信息
      columns: [
        { key: 0, label: `状态`, prop: "status", visible: true },
        { key: 1, label: `活动名称`, prop: "activityName", visible: true },
        { key: 2, label: `发起单位`, prop: "organizationName", visible: true },
        { key: 3, label: `主办单位`, prop: "sponsor", visible: true },
        { key: 4, label: `类别`, prop: "type", visible: true },
        { key: 5, label: `形式`, prop: "lays", visible: true },
        { key: 6, label: `发起时间`, prop: "initiationTime", visible: true},
        { key: 7, label: `开始时间`, prop: "startTime", visible: true},
        { key: 8, label: `结束时间`, prop: "endTime", visible: true},
        { key: 9, label: `地点`, prop: "location", visible: true },
        { key: 10, label: `创建人`, prop: "creationName", visible: true },
        { key: 11, label: `创建时间`, prop: "creationTime", visible: true,},
        { key: 12, label: `联系人`, prop: "contacts", visible: true },
        { key: 13, label: `联系电话`, prop: "telephone", visible: true },
        { key: 14, label: `报名截止`, prop: "deadlineTime",visible: true},
        { key: 15, label: `审核人`, prop: "examineName", visible: true },
        { key: 16, label: `参训人数`, prop: "partPersonNum", visible: true },
        { key: 17, label: `参训企业数量`, prop: "partEnterNum", visible: true },
        { key: 18,label:"报名企业数",prop:"partEnterNum", visible: true },
        { key: 19, label: `满意度平均分`, prop: "satisfactionScore", visible: true },
        { key: 20, label: `费用`, prop: "fee", visible: true }
      ],

      // 表单参数
      form: {},
    };
  },
  created() {
    this.getList();
    this.listType();
    this.area();
  },
  methods: {
    /** 查询活动信息培训列表 */
    getList() {
      listTrainingExamine(this.queryParams).then(response => {
        this.trainingList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    //获取树节点数据
    listType(){
      listType({typeCode:'train'}).then(res=>{
        console.log(res);
        this.options=res.data;
      })
    },
    selectUser(userId,userName){
      this.$set(this.form, 'examineId', userId)
      this.$set(this.form, 'examineName', userName)
    },
    //关闭对话框
    closeTrain(){
      this.ReadOnly=false;
      this.examineRead=false;
      this.show=false;
      this.open=false;
    },
    area(){
      listArea({}).then(response => {
        this.optionsArea = response.data;
      });
    },
    normalizer(node){
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id:node.areaId,
        label:node.areaName,
        isDisabled:false,
        children:node.list.length>0?node.list:0,
      }
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    parseUTCTime(time, format) {
      const date = new Date(time.replace('T', ' ').replace('+08', ''));
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      const hours = String(date.getHours()).padStart(2, '0');
      const minutes = String(date.getMinutes()).padStart(2, '0');
      return format.replace('{y}', year).replace('{m}', month).replace('{d}', day).replace('{hh}', hours).replace('{mm}', minutes);
    },
    //转商机
    convertBusiness(row){
      this.convertBuiness=true;
    },
    closeEle(){
      this.convertBuiness=false;
    },
    //点击接收方文本域,弹出选择当前用户在企业管理中的企业信息
    handleTextAreaFocus() {
      this.openUser=true;
    },
    selectOpen(type){
      this.userType=1;
      this.$refs.select.show();
    },
    //获取当前用户在企业管理中的企业信息
    selectEnterprise(selection){
      this.form.enterpriseId = selection.map(item => item.enterpriseId);
      this.form.receiverName = selection.map(item => item.enterpriseName).join('\n'); // 修改这里
      console.log(this.form)
      this.close()
    },
    close(){
      this.openUser=false
    },
    // 表单重置
    reset() {
      this.form = {
        activityId: null,
        activityName: null,
        initiationUnit: null,
        sponsor: null,
        type: null,
        initiationTime: null,
        lays: null,
        startTime: null,
        endTime: null,
        location: null,
        receiverId: null,
        receiverName: null,
        operateTime: null,
        status: null,
        operateId: null,
        operateName: null,
        departmentId: null,
        departmentName: null,
        organizationId: null,
        organizationName: null,
        createId: null,
        creationName: null,
        creationTime: null,
        belongTo: null,
        classificationId: null,
        contacts: null,
        telephone: null,
        deadlineTime: null,
        examineId: null,
        examineName: null,
        fileUpload: null,
        partPersonNum: null,
        partEnterNum: null,
        satisfactionScore: null,
        //客户id数组
        enterpriseId:[],
        sendType:null,
        region:null,
        activityPicture:null,
        examineStatus:null,
        endReason:null,
        version:null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },

    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.queryParams.initStartTime=null;
      this.queryParams.initEndTime=null;
      this.handleQuery();
    },
    //树点击事件
    getNode(data,node,obj){
      console.log(data)
      if(data.parentId!='00000000-0000-0000-0000-000000000000'){
        this.queryParams.classificationId=data.id
      }else {
        this.queryParams.classificationId=null
      }
      this.getList()
    },
    //当有值的时候，默认打开对话框为分类群发，没值为一键发送
    sendTrain(){
      if (this.form.receiverName!==null){
        this.sendType="groupSend"
      }else {
        this.sendType="oneClick"
      }
    },
    //序号展示
    indexMethod(index){
      return (this.queryParams.pageNum-1)*this.queryParams.pageSize +index+1;
    },
    /** 审核按钮操作 */
    handleSelect(row,index) {
      this.reset();
      const activityId = row.activityId || this.ids
        getTraining(activityId).then(response => {
          this.form = response.data;
          this.ReadOnly=true;
          this.open = true;
          this.typeSelect=2;
          this.typeSelect2=0;
          this.form.index=index+1;
          this.addSign=2;
          this.show=true;
          this.title = "审核活动信息培训";
        })
    },
    //查看
    handleScore(row,index){
      const activityId = row.activityId || this.ids
      getTraining(activityId).then(response => {
        this.form = response.data;
        this.ReadOnly=true;
        this.examineRead=true;
        this.open = true;
        this.typeSelect=2;
        this.typeSelect2=1;
        this.form.index=index+1;
        this.addSign=3;
        this.show=true;
        this.title = "活动信息培训查看";
      });
    },
    /** 审核按钮 */
    submitForm(activityId) {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.examineStatus==='through'){
            examine(this.form).then(res=>{
              if (res.code===200){
                this.$message.success("审核成功");
                this.show=false;
                this.open=false;
                this.getList();
              }else {
                this.$message.error("审核失败,请刷新数据后重新尝试");
                this.show=false;
                this.open=false;
                this.getList();
              }
            })
          }else {
            endStatus(this.form).then(res=>{
              if (res.code===200){
                this.$message.success("终止成功");
                this.show=false;
                this.open=false;
                this.getList();
              }else {
                this.$message.error("终止失败,请刷新数据后重新尝试");
                this.show=false;
                this.open=false;
                this.getList();
              }
            })
          }
        }
      });
    },
    //判断活动当前日期是否大于报名日期
    isBeforeDeadline(deadlineTime) {
      const currentTime = new Date();
      const date = new Date(deadlineTime);
      return date>currentTime;
    },
  }
};
</script>
